from datetime import datetime, date
from typing import List, Optional
from sqlalchemy.orm import Session
from ..models.attendance import AttendanceRecord as AttendanceRecordModel
from ..models.user import User
from ..schemas.attendance import AttendanceCreate, AttendanceUpdate

class AttendanceService:
    def __init__(self, db: Session):
        self.db = db

    def get_attendance_record_by_date(self, user_id: int, record_date: str) -> Optional[AttendanceRecordModel]:
        """根据用户ID和日期获取考勤记录"""
        return self.db.query(AttendanceRecordModel).filter(
            AttendanceRecordModel.user_id == user_id,
            AttendanceRecordModel.date == record_date
        ).first()

    def create_attendance_record(self, attendance_data: AttendanceCreate) -> AttendanceRecordModel:
        """创建考勤记录"""
        db_attendance = AttendanceRecordModel(**attendance_data.dict())
        self.db.add(db_attendance)
        self.db.commit()
        self.db.refresh(db_attendance)
        return db_attendance

    def update_attendance_record(self, attendance_id: int, attendance_data: AttendanceUpdate) -> Optional[AttendanceRecordModel]:
        """更新考勤记录"""
        db_attendance = self.db.query(AttendanceRecordModel).filter(
            AttendanceRecordModel.id == attendance_id
        ).first()
        if db_attendance:
            for key, value in attendance_data.dict(exclude_unset=True).items():
                setattr(db_attendance, key, value)
            db_attendance.updated_at = datetime.utcnow()
            self.db.commit()
            self.db.refresh(db_attendance)
        return db_attendance

    def clock_in(self, user_id: int) -> AttendanceRecordModel:
        """用户打卡上班"""
        current_date = date.today().strftime("%Y-%m-%d")
        current_time = datetime.now()
        
        # 检查今天是否已经打卡
        existing_record = self.get_attendance_record_by_date(user_id, current_date)
        
        if existing_record:
            if existing_record.clock_in_time:
                # 已经打卡过了
                return existing_record
            else:
                # 更新现有记录的打卡时间
                existing_record.clock_in_time = current_time
                existing_record.updated_at = datetime.utcnow()
                # 判断是否迟到（假设9点上班）
                work_time = current_time.replace(hour=9, minute=0, second=0, microsecond=0)
                if current_time > work_time:
                    existing_record.status = "迟到"
                self.db.commit()
                self.db.refresh(existing_record)
                return existing_record
        else:
            # 创建新的打卡记录
            attendance_data = AttendanceCreate(
                user_id=user_id,
                clock_in_time=current_time,
                date=current_date,
                status="正常"
            )
            # 判断是否迟到（假设9点上班）
            work_time = current_time.replace(hour=9, minute=0, second=0, microsecond=0)
            if current_time > work_time:
                attendance_data.status = "迟到"
            return self.create_attendance_record(attendance_data)

    def clock_out(self, user_id: int) -> Optional[AttendanceRecordModel]:
        """用户打卡下班"""
        current_date = date.today().strftime("%Y-%m-%d")
        current_time = datetime.now()
        
        # 检查今天是否有打卡记录
        existing_record = self.get_attendance_record_by_date(user_id, current_date)
        
        if existing_record:
            # 更新现有记录的下班打卡时间
            existing_record.clock_out_time = current_time
            existing_record.updated_at = datetime.utcnow()
            self.db.commit()
            self.db.refresh(existing_record)
            return existing_record
        else:
            # 没有上班打卡记录，无法下班打卡
            return None

    def get_user_attendance_records(self, user_id: int, start_date: Optional[str] = None, 
                                   end_date: Optional[str] = None) -> List[AttendanceRecordModel]:
        """获取用户的考勤记录"""
        query = self.db.query(AttendanceRecordModel).filter(
            AttendanceRecordModel.user_id == user_id
        )
        
        if start_date:
            query = query.filter(AttendanceRecordModel.date >= start_date)
        if end_date:
            query = query.filter(AttendanceRecordModel.date <= end_date)
        
        # 按日期降序排序
        return query.order_by(AttendanceRecordModel.date.desc()).all()

    def get_department_attendance_summary(self, department_id: int, 
                                         start_date: Optional[str] = None, 
                                         end_date: Optional[str] = None) -> dict:
        """获取部门考勤汇总"""
        # 获取部门下的所有用户
        users = self.db.query(User).filter(User.department_id == department_id).all()
        user_ids = [user.id for user in users]
        
        # 查询这些用户的考勤记录
        query = self.db.query(AttendanceRecordModel).filter(
            AttendanceRecordModel.user_id.in_(user_ids)
        )
        
        if start_date:
            query = query.filter(AttendanceRecordModel.date >= start_date)
        if end_date:
            query = query.filter(AttendanceRecordModel.date <= end_date)
        
        records = query.all()
        
        # 计算汇总信息
        total_days = len(set(record.date for record in records)) * len(user_ids)
        on_time_days = len([r for r in records if r.status == "正常" and r.clock_in_time])
        late_days = len([r for r in records if r.status == "迟到" and r.clock_in_time])
        # 计算缺勤天数（应该打卡但未打卡的天数）
        # 这里简化处理，实际可能需要更复杂的计算
        absent_days = 0
        
        return {
            "total_days": total_days,
            "on_time_days": on_time_days,
            "late_days": late_days,
            "absent_days": absent_days,
            "department_id": department_id
        }